package org.example.thread;

import lombok.extern.slf4j.Slf4j;
import org.example.config.ThreadConfig;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;

@Slf4j
public class ThreadPoolManager {
    // 用于查询tb设备数据计算在线设备
    public static ExecutorService executorService;
    // todo 完善丢弃策略以及任务队列，根据需求修改核心线程数和最大线程数
    // 用于提交异步任务(如提交设备到redis)
    private static final ThreadPoolExecutor asyncExecutor=new ThreadPoolExecutor(
            // 核心线程未满就创建核心线程执行任务，多于核心线程数就会提交到workQueue
            // 超过workQueue未达最大线程就会创建非核心线程，超过最大线程数就会按策略处理未执行的任务
            ThreadConfig.CORE_POOL_SIZE, ThreadConfig.MAX_POOL_SIZE,
            ThreadConfig.KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
            // 任务队列和丢弃策略待定
            new SynchronousQueue<>(), new ThreadPoolExecutor.AbortPolicy());

    static {
        int corePoolSize=Runtime.getRuntime().availableProcessors(); // 获取核心线程数，使用机器处理器核心数量
        log.info("线程池创建{}",corePoolSize);
        executorService = Executors.newFixedThreadPool(2*corePoolSize);  // 线程池大小设置为核心线程数的两倍
    }

    public static void executeAsync(Runnable task){
        asyncExecutor.execute(task);
    }

    public static void shutdown(){
        executorService.shutdown();
        asyncExecutor.shutdown();
    }



}
